package com.rolerealm.service.impl;

import com.rolerealm.service.LLMService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * 阿里云通义千问（DashScope） LLM 实现
 */
@Slf4j
@Service
public class DashScopeLLMServiceImpl implements LLMService {

    @Value("${llm.dashscope.apiKey:}")
    private String apiKey;

    @Value("${llm.dashscope.baseUrl:https://dashscope.aliyuncs.com}")
    private String baseUrl;

    @Value("${llm.dashscope.model:qwen-turbo}")
    private String defaultModel;

    @Value("${llm.dashscope.timeoutSeconds:30}")
    private int timeoutSeconds;

    private final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    @Override
    public String infer(String prompt, String languageOrModel) {
        if (apiKey == null || apiKey.isBlank()) {
            log.warn("DashScope API Key 未配置，回退到简单回声");
            return "AI回复：" + (prompt == null ? "" : prompt);
        }

        // 通义千问模型列表
        String[] models = {"qwen-max", "qwen-plus", "qwen-turbo"};
        
        // 构建API URL
        String url = baseUrl.endsWith("/") ? 
            (baseUrl + "api/v1/services/aigc/text-generation/generation") : 
            (baseUrl + "/api/v1/services/aigc/text-generation/generation");

        // 尝试多个模型
        for (String tryModel : models) {
            try {
                String requestBody = "{\n" +
                        "  \"model\": \"" + escape(tryModel) + "\",\n" +
                        "  \"input\": {\n" +
                        "    \"messages\": [\n" +
                        "      {\"role\": \"system\", \"content\": \"You are RoleRealm AI assistant.\"},\n" +
                        "      {\"role\": \"user\", \"content\": " + toJsonString(prompt) + "}\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  \"parameters\": {\n" +
                        "    \"temperature\": 0.7,\n" +
                        "    \"max_tokens\": 2000\n" +
                        "  }\n" +
                        "}";

                log.debug("尝试调用通义千问模型: {}, URL: {}", tryModel, url);

                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(url))
                        .timeout(Duration.ofSeconds(Math.max(5, timeoutSeconds)))
                        .header("Authorization", "Bearer " + apiKey)
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
                        .build();

                HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
                log.debug("通义千问模型 {} 响应状态: {}, 响应体: {}", tryModel, response.statusCode(), response.body());
                
                if (response.statusCode() / 100 == 2) {
                    String resp = response.body();
                    String content = extractContentFromDashScopeResponse(resp);
                    if (content != null && !content.isBlank()) {
                        log.info("成功使用通义千问模型: {}", tryModel);
                        return content;
                    }
                } else {
                    log.warn("通义千问模型 {} 调用失败，status={} body={}", tryModel, response.statusCode(), response.body());
                }
            } catch (Exception e) {
                log.warn("通义千问模型 {} 调用异常: {}", tryModel, e.getMessage());
            }
        }
        
        log.error("所有通义千问模型都调用失败，回退到简单回声");
        return fallback(prompt);
    }

    private String fallback(String prompt) {
        return "AI回复：" + (prompt == null ? "" : prompt);
    }

    private static String toJsonString(String text) {
        if (text == null) return "\"\"";
        String esc = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
        return "\"" + esc + "\"";
    }

    private static String escape(String s) {
        return s == null ? "" : s.replace("\"", "");
    }

    // 解析DashScope API响应
    private static String extractContentFromDashScopeResponse(String json) {
        if (json == null) return null;
        
        try {
            log.debug("开始解析DashScope响应: {}", json);
            
            // 查找 "output" -> "text" 字段
            int outputIdx = json.indexOf("\"output\"");
            if (outputIdx < 0) {
                log.warn("响应中未找到output字段");
                return null;
            }
            
            int textIdx = json.indexOf("\"text\"", outputIdx);
            if (textIdx < 0) {
                log.warn("响应中未找到text字段");
                return null;
            }
            
            int colonIdx = json.indexOf(':', textIdx);
            if (colonIdx < 0) {
                log.warn("text字段后未找到冒号");
                return null;
            }
            
            int startQuote = json.indexOf('"', colonIdx + 1);
            if (startQuote < 0) {
                log.warn("text字段值未找到开始引号");
                return null;
            }
            
            StringBuilder sb = new StringBuilder();
            boolean escape = false;
            for (int i = startQuote + 1; i < json.length(); i++) {
                char ch = json.charAt(i);
                if (escape) {
                    switch (ch) {
                        case 'n': sb.append('\n'); break;
                        case 'r': sb.append('\r'); break;
                        case 't': sb.append('\t'); break;
                        case '"': sb.append('"'); break;
                        case '\\': sb.append('\\'); break;
                        default: sb.append(ch); break;
                    }
                    escape = false;
                } else {
                    if (ch == '\\') { 
                        escape = true; 
                        continue; 
                    }
                    if (ch == '"') break;
                    sb.append(ch);
                }
            }
            
            String result = sb.toString();
            log.debug("解析DashScope响应成功，提取内容: {}", result);
            return result;
        } catch (Exception e) {
            log.warn("解析DashScope响应失败: {}", e.getMessage());
            return null;
        }
    }
}
